package model.db;

import model.db.DB;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.User;
import model.Users;

/**
 *
 * @author user
 */
public class FriendsDB extends DB {

    public Users find(int userId) {
        Users friends = new Users();

        try {
            query =
                    "SELECT user.id, user.username, user.role "
                    + "FROM user JOIN friend ON user.id = friend.friend_id "
                    + "WHERE friend.user_id = " + userId;
            System.out.println(query);
            rs = statement.executeQuery(query);
            User user;
            int friendId = 0;
            while (rs.next()) {
                friendId = Integer.parseInt(rs.getString(1));
                user = new User(friendId, rs.getString(2), rs.getString(3));
                friends.add(user);
            }
        } catch (SQLException ex) {
            Logger.getLogger(FriendsDB.class.getName()).log(Level.SEVERE, null, ex);
        }

        return friends;
    }

    public boolean isFriend(int userId, int friendId) {
        boolean isFriend = false;

        try {
            query = "SELECT * "
                    + "FROM friend "
                    + "WHERE user_id=" + userId + " AND friend_id=" + friendId;
            rs = statement.executeQuery(query);

            isFriend = rs.next();
        } catch (SQLException ex) {
            Logger.getLogger(FriendsDB.class.getName()).log(Level.SEVERE, null, ex);
        }

        return isFriend;
    }

    public boolean addFriend(int userId, String friendUsername) {
        try {
            query = "SELECT id FROM user WHERE username='" + friendUsername + "'";
            rs = statement.executeQuery(query);

            if (rs.next()) {
                int friendId = (Integer) rs.getObject(1);

                query = "INSERT INTO friend(user_id, friend_id) VALUE(" + userId + ", " + friendId + ")";
                System.out.println(query);
                statement.executeUpdate(query);
            } else {
                return false;
            }
        } catch (SQLException ex) {
            Logger.getLogger(FriendsDB.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }

        return true;
    }
}
